package servlet;

import com.alibaba.fastjson.JSON;
import entity.User;
import service.BooksService;
import service.UserService;
import service.impl.BooksServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        UserService userService = new UserServiceImpl();

        String opr = req.getParameter("opr");
        Map map = new HashMap();
        String mapJson = "";

        if (opr.equals("add")){
            String uname = req.getParameter("uname");
            String uno = req.getParameter("uno");
            String pwd = req.getParameter("pwd");
            System.out.println(uname);
        }else if (opr.equals("user")){
            int uid = Integer.parseInt(req.getParameter("uid"));
            ResultSet rs = userService.selectUser(uid);
            User user = new User();
            try{
                while (rs.next()){
                    uid = rs.getInt("uid");
                    String uno = rs.getString("uno");
                    String uname = rs.getString("uname");
                    String pwd = rs.getString("pwd");
                    String sex = rs.getString("sex");
                    String photo = rs.getString("photo");
                    user.setUid(uid);
                    user.setUno(uno);
                    user.setUname(uname);
                    user.setPwd(pwd);
                    user.setSex(sex);
                    user.setPhoto(photo);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            map.put("user",user);

            mapJson = JSON.toJSONString(map);
            out.print(mapJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
